<template>
  <div>
    <van-address-list
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @select="selectHandle"
    />
    <van-empty v-if="list.length === 0" description="请先完善收获地址" />
  </div>
</template>

<script>
import { fetchGetUserAddress } from "@/api/address.js";
export default {
  data() {
    return {
      chosenAddressId: "", // 默认地址
      list: [],
    };
  },
  created() {
    //   加载个人收获地址
    this._fetchUserAddress();
  },
  methods: {
    async _fetchUserAddress() {
      let user_id = this.$store.state.userInfo.id;
    console.log(user_id)
      let addressAll = await fetchGetUserAddress(user_id);
      // 把默认地址排在第一位
      addressAll = addressAll.map((item) => {
        // 额外设置一个属性，保存省市区的编码
        item.fullAreaCode = item.areaCode;
        item.areaCode = item.areaCode.split("-")[2];
        if (item.isDefault) {
          // 显示默认文字
          item.isDefault = true;
        } else {
          item.isDefault = false;
        }
        return item;
      });
      let index = addressAll.findIndex((item) => item.isDefault == true);
      console.log(addressAll)
      if (index !== -1) {
        let defaultAddress = addressAll[index];
        // 设置地址勾选
        this.chosenAddressId = defaultAddress.id;
        addressAll.splice(index, 1); // 删除
        addressAll.unshift(defaultAddress); // 添加到头部
      } else {
        this.chosenAddressId = addressAll[1].id;
      }
      this.list = addressAll;
    },
    //dianji
    onAdd() {
      this.$router.push("/addMyress");
    },
    onEdit(item, index) {
      this.$toast("编辑地址:" + index);
      this.$router.push("/editMyress/" + JSON.stringify(this.list[index]));
    },
    // 切换选中的地址
    selectHandle(addressInfo, index) {
      // 1. 把当前选中的地址存入到本地存储
      localStorage.setItem("harvestAddress", JSON.stringify(addressInfo));
      // 2.返回是一页面
      this.$router.back();
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
